/**
 * Created by hejg on 2018/5/9.
 */
import React, {Component} from 'react';
import {
    Platform, StatusBar, Dimensions,
    StyleSheet, Image,
    Text, TextInput,
    View, TouchableOpacity, Alert, AsyncStorage
} from 'react-native';
import {observer} from 'mobx-react/native';
import {observable, computed, action} from 'mobx';

@observer
export default class FormInput extends Component {
    @observable
    countdown = 0;

    @computed
    get canSendMark() {
        return this.countdown < 1;
    }

    @action
    setCountdown(countdown) {
        this.countdown = countdown;
    }

    constructor(props) {
        super(props);
        this._refreshCountdown();
    }

    componentWillUnmount() {
        this.interval && clearInterval(this.interval);
    }

    _handleSendMark() {
        this.props.form.setValue('valicode', '');
        this.props.onSendMarkEvent();
        this._refreshCountdown();
    }

    _refreshCountdown() {
        this.props.form.setValue('valicode', '');
        this.setCountdown(60);
        this.interval = setInterval(() => {
            if (this.countdown == 1) {
                clearInterval(this.interval);
                this.setCountdown(0);
            } else {
                this.setCountdown(this.countdown - 1);
            }
        }, 1000);
    }

    render() {
        const {form, name, sendMark, titleCN, titleSP, titleUS, secureTextEntry, keyboardType} = this.props;
        return (
            <View>
                <View style={{flexDirection:'row',marginTop:15,marginBottom:0}}>
                    <Text style={{color:'#000000'}}>{titleCN}</Text>
                    <Text> {titleSP} </Text>
                    <Text>{titleUS}</Text>
                </View>
                <View style={{flexDirection:'row',borderBottomWidth:1,borderColor:'#DDDDDD'}}>
                    <TextInput
                        placeholder={'请输入'+titleCN}
                        underlineColorAndroid='transparent'
                        style={{flex:1,height:35,padding:0}}
                        onChangeText={(text) => form.setValue(name,text)}
                        value={form[name]}
                        secureTextEntry={secureTextEntry? true : false}
                        keyboardType={keyboardType ? 'numeric' : 'default'}
                    />
                    {sendMark ? (
                            <TouchableOpacity
                                disabled={!this.canSendMark}
                                onPress={this._handleSendMark.bind(this)}
                                style={{paddingVertical:8}}>
                                <Text
                                    style={this.canSendMark?{color:'#00A0FF'}:{}}>{this.canSendMark ? '获取' : this.countdown + '秒'}</Text>
                            </TouchableOpacity>) : null}
                </View>
            </View>
        )
    }
}